package aufgabe2;

import java.security.*;
import java.security.acl.Permission;

/**
 * Handling Access to Courses - uses the Singleton Pattern
 * 
 * @author Lukas Koell
 * @author David Medenjak
 * @author Johannes Riedmann
 */
public class AccessManager {

    private static AccessManager instance;

    private static Principal currentPrincipal;

    private static aufgabe2.Acl acl;

    /**
     * private constructor so clients have to use @link:getInstance()
     */
    private AccessManager() {
        acl = new aufgabe2.Acl();
    }

    /**
     * getter for the instance of the singleton
     * 
     * @return the one and only instance of this class
     */
    public static AccessManager getInstance() {
        if (instance == null) {
            instance = new AccessManager();
        }
        return instance;
    }

    /**
     * sets the current User for whom to check permissions
     * 
     * @param user
     *            TODO: add other usergroups when needed
     */
    public void setUser(Principal user) {
        currentPrincipal = user;
        String userClass = user.getClass().toString();

        if (userClass.equals("class aufgabe2.Student")) {
            acl.addUserToGroup(currentPrincipal, "students");
        } else if (userClass.equals("class aufgabe2.Teacher")) {
            acl.addUserToGroup(currentPrincipal, "teachers");
        } else if (userClass.equals("class aufgabe2.Admin")) {
            acl.addUserToGroup(currentPrincipal, "admins");
        }

    }

    /**
     * checks if a user has access to a certain resource resource is made up
     * from an object and a method
     * 
     * @throws AccessDeniedException
     *             if permissions are not met
     */
    public void checkAccess(Permission permission) throws AccessDeniedException {
        if (!acl.checkPermission(currentPrincipal, permission)) {
            throw new AccessDeniedException("permission "
                    + permission.toString() + " not allowed " + "for user "
                    + currentPrincipal);
        }
    }

    public Principal getUser() {
        return currentPrincipal;
    }
}
